/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.coupon.factory;

import cn.icanci.basic.exception.ApplicationException;
import cn.icanci.coupon.entity.CouponEntity;
import cn.icanci.coupon.error.CouponError;
import cn.icanci.coupon.form.BeCouponForm;
import cn.icanci.coupon.model.Coupon;
import cn.icanci.coupon.repository.CouponRepository;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

/**
 * 优惠券实体工厂
 *
 * @author icanci
 * @date Created in 2021/05/01 10:01
 * @version 1.0
 */
@Component
public class CouponFactory {
    @Resource
    CouponRepository couponRepository;

    /**
     * 构建实体
     * @param couponForm
     * @return
     */
    public CouponEntity create(BeCouponForm couponForm) {
        CouponEntity couponEntity = new CouponEntity(couponRepository);
        BeanUtils.copyProperties(couponForm, couponEntity);
        couponEntity.setCreateTime(new Date());
        couponEntity.setUpdateTime(new Date());
        couponEntity.setStatus(1);
        couponEntity.setDeleted(1);
        return couponEntity;
    }

    /**
     * 构建实体
     * @param uniqueKey
     * @return
     */
    public CouponEntity create(String uniqueKey) throws ApplicationException {
        Coupon coupon = couponRepository.findByUniqueKey(uniqueKey);
        if (null == coupon) {
            throw new ApplicationException(20001, CouponError.COUPON_NOT_EXIST.getDesc());
        }
        CouponEntity couponEntity = new CouponEntity(couponRepository);
        BeanUtils.copyProperties(coupon, couponEntity);
        return couponEntity;
    }

    /**
     * 构建实体
     * @param couponNumber
     * @return
     */
    public CouponEntity createByCouponNumber(String couponNumber) throws ApplicationException {
        Coupon coupon = couponRepository.queryOneByCouponNumber(couponNumber);
        if (null == coupon) {
            throw new ApplicationException(20001, CouponError.COUPON_NOT_EXIST.getDesc());
        }
        CouponEntity couponEntity = new CouponEntity(couponRepository);
        BeanUtils.copyProperties(coupon, couponEntity);
        return couponEntity;
    }
    //
}
